package com.shuoyue.ycgk.ui.pay;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ahammertest.ycgk.pay.PaySucEvent;
import com.ahammertest.ycgk.pay.alipay.Alipay;
import com.ahammertest.ycgk.pay.alipay.PayResult;
import com.ahammertest.ycgk.wxapi.WxPay;
import com.ahammertest.ycgk.wxapi.WxPayBean;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.entity.Coupon;
import com.shuoyue.ycgk.entity.Rule;
import com.shuoyue.ycgk.entity.address.OrderAddressBean;
import com.shuoyue.ycgk.ui.common.RuleContract;
import com.shuoyue.ycgk.ui.mine.coupon.CouponSelectActivity;
import com.shuoyue.ycgk.ui.shop.address.SelectAddressActivity;
import com.shuoyue.ycgk.utils.MyRichTextHelper;
import com.shuoyue.ycgk.utils.XToast;
import com.shuoyue.ycgk.views.dialog.common.HintDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public abstract class BasePreOrderActivity extends BaseMvpActivity<PreOrderContract.Presenter>
        implements PreOrderContract.View, RuleContract.View {
    protected OrderPriceInfo orderPriceInfo;
    PreGoodsAdapter adapter;
    GoodsItem goodsItem;
    int max = 0;
    OrderNo orderNo;
    protected OrderAddressBean addressInfo;

    @BindView(R.id.rule)
    TextView rule;
    @BindView(R.id.page_title)
    TextView pageTitle;
    @BindView(R.id.address_name)
    TextView addressName;
    @BindView(R.id.address_phone)
    TextView addressPhone;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.lay_address)
    RelativeLayout layAddress;
    @BindView(R.id.data_recycleView)
    RecyclerView dataRecycleView;
    @BindView(R.id.num_sum1)
    TextView numSum1;
    @BindView(R.id.price_total)
    TextView priceTotal;
    @BindView(R.id.buyNum)
    TextView buyNum;
    @BindView(R.id.layBuyNum)
    LinearLayout layBuyNum;
    @BindView(R.id.post_price)
    TextView postPrice;
    @BindView(R.id.layPostPrice)
    LinearLayout layPostPrice;
    @BindView(R.id.coupon)
    TextView coupon;
    @BindView(R.id.layCoupon)
    LinearLayout layCoupon;
    @BindView(R.id.message)
    EditText message;
    @BindView(R.id.layMessage)
    LinearLayout layMessage;
    @BindView(R.id.wx_pay)
    CheckBox wxPay;
    @BindView(R.id.alpay)
    CheckBox alpay;
    @BindView(R.id.buy)
    TextView buy;
    @BindView(R.id.pay_price)
    TextView payPrice;
    //    @BindView(R.id.remark)
//    protected EditText remark;
    Coupon selectCoupon;
    RuleContract.Presenter rulePresenter;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_pre_order;
    }

    @Override
    protected void initView() {
        pageTitle.setText("确认订单");
        dataRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new PreGoodsAdapter(null);
        dataRecycleView.setAdapter(adapter);
    }

    @Override
    public void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        mPresenter = new PreOrderContract.Presenter();
        mPresenter.attachView(this);
        rulePresenter = new RuleContract.Presenter();
        rulePresenter.attachView(this);
        rulePresenter.getRule(6);
    }

    @OnClick({R.id.back, R.id.lay_address,
            R.id.layCoupon, R.id.buy,
            R.id.tv_add, R.id.tv_reduce,
            R.id.lay_wx, R.id.wx_pay, R.id.lay_ali, R.id.alpay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.lay_address:
                startActivityForResult(new Intent(mContext, SelectAddressActivity.class)
                                .putExtra("type", 1)
                                .putExtra("id", orderPriceInfo == null || orderPriceInfo.getDeliveryAddress() == null ?
                                        -1 : orderPriceInfo.getDeliveryAddress().getId()),
                        1043);
                break;
            case R.id.layCoupon:
                getCoupon();
                break;
            case R.id.buy:
                buy();
                break;
            case R.id.tv_add:
                if (goodsItem.getNum() < max) {
                    goodsItem.setNum(goodsItem.getNum() + 1);
                    buyNum.setText(goodsItem.getNum() + "");
                    resetNum(goodsItem.getNum());
                }
                break;
            case R.id.tv_reduce:
                if (goodsItem.getNum() > 1) {
                    goodsItem.setNum(goodsItem.getNum() - 1);
                    buyNum.setText(goodsItem.getNum() + "");
                    resetNum(goodsItem.getNum());
                }
                break;
            case R.id.lay_wx:
            case R.id.wx_pay:
                switchPayType(1);
                break;
            case R.id.lay_ali:
            case R.id.alpay:
                switchPayType(2);
        }
    }

    abstract void getCoupon();

    //1:微信;2阿里
    void switchPayType(int type) {
        if (type == 1) {
            wxPay.setChecked(true);
            alpay.setChecked(false);
        } else {
            wxPay.setChecked(false);
            alpay.setChecked(true);
        }

    }

    void buy() {
//        buy.setEnabled(false);
        Log.e("buy点击了", "==========>");
        if (orderPriceInfo == null) {
            return;
        }
        if (addressInfo == null) {
            toast("请输入邮寄资料收货地址");
            return;
        }
        int payType = 0;
        if (wxPay.isChecked()) {
            payType = 1;
        } else if (alpay.isChecked()) {
            payType = 2;
        }
        if (payType == 0) {
            XToast.toast(mContext, "请选择支付方式");
        } else {
            buy.setEnabled(false);
            initOrderParams(payType);
        }
    }

    protected void setBuyItemAdapter() {
        this.goodsItem = createGoodsItem();
        List<GoodsItem> goodsItems = new ArrayList<>();
        goodsItems.add(goodsItem);
        adapter.resetData(goodsItems);
    }


    protected void enableAddressSelect() {
        layAddress.setVisibility(View.VISIBLE);
    }

    protected void enableNumSelect() {
        layBuyNum.setVisibility(View.VISIBLE);
    }

    protected void setMax(int max) {
        this.max = max;
    }

    protected void setPostPrice(float price) {
        layPostPrice.setVisibility(View.VISIBLE);
        if (price == 0) {
            postPrice.setText("快递  免邮");
        } else {
            postPrice.setText("快递  ￥" + price);
        }
    }

    protected void setCouponText(String text) {
        coupon.setText(text);
    }

    protected void enAbleCouponSelect() {
        layCoupon.setVisibility(View.VISIBLE);
    }

    protected void enableMessageLayout() {
        layMessage.setVisibility(View.VISIBLE);
    }

    protected void setPriceToatle(int buyNum, float totalPricef, float payPricef) {
        numSum1.setText("共" + buyNum + "件");
        payPrice.setText("￥" + payPricef);
        priceTotal.setText("￥" + totalPricef);
    }

    protected void setGoodsPrice(String price) {
        for (GoodsItem goodsItem : adapter.getData()) {
            goodsItem.setPrice(price);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void setPriceInfo(OrderPriceInfo priceInfo) {
        this.orderPriceInfo = priceInfo;
        if (priceInfo.getHasCoupon() == 0) {
            coupon.setText("暂无可用优惠券");
        } else {
            if (priceInfo.getCouponPrice() == 0) {
                coupon.setText("请选择");
            } else {
                coupon.setText("已优惠:￥" + priceInfo.getCouponPrice());
            }

        }
    }

    @Override
    public void getPriceInfoFail() {
        selectCoupon = null;
    }

    @Override
    public void createOrderSuc(OrderNo orderCode, int type) {
        this.orderNo = orderCode;
        if (orderCode == null) {
            //直接成功
            HintDialog hintDialog = new HintDialog(mContext, "提示", "领取成功");
            hintDialog.setOkListener(v -> {
                hintDialog.dismiss();
                finish();
            });
            hintDialog.setCancelable(false);
            hintDialog.setCanceledOnTouchOutside(false);
            hintDialog.show();
        } else {
//        XToast.toast(mContext, "订单编号:" + orderCode.getOrderNo());
            if (type == 1) {
                mPresenter.getWxPayInfo(orderCode.getOrderNo());
            } else {
                mPresenter.getAliPayInfo(orderCode.getOrderNo());
            }
        }
    }

    @Override
    public void getWxPayInfoSuc(WxPayBean o) {
        WxPay.pay(this, o);
    }

    @Override
    public void enableButtonPay() {
        buy.setEnabled(true);
    }

    abstract GoodsItem createGoodsItem();

    abstract void resetNum(int num);

    abstract void initOrderParams(int payType);

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void PayResult(PaySucEvent event) {
        if (event.getPayStatus() == 1) {
            PaySucActivity.start(mContext, orderNo.getOrderNo());
            finish();

        } else {
//            XToast.toast(mContext, "支付失败,请联系客服");
        }

    }

    @Override
    public void getAliPaySuc(String info) {
        Alipay.pay(this, info, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    PayResult payResult = (PayResult) msg.obj;
                    Log.e("alipay", payResult.toString());
                    try {
                        JSONObject jsonObject = new JSONObject(payResult.getResult());
                        JSONObject resultcodes = jsonObject.optJSONObject("alipay_trade_app_pay_response");
                        String code = resultcodes.optString("code");
                        Log.e("code", code);
                        if (code.equals("10000")) {
                            PayResult(new PaySucEvent(1));
                        } else {
                            PayResult(new PaySucEvent(2));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        PayResult(new PaySucEvent(2));
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1044 && resultCode == RESULT_OK) {
            selectCoupon = (Coupon) data.getSerializableExtra("data");
            resetNum(goodsItem.getNum());
        } else if (requestCode == 1043) {
            if (resultCode == RESULT_OK) {
                OrderAddressBean orderAddressBean = (OrderAddressBean) data.getSerializableExtra("add");
                if (orderAddressBean != null) {
                    setAddressInfo(orderAddressBean);
                    return;
                }
            }
            setAddressInfo(null);
        }
    }


    void setAddressInfo(OrderAddressBean addressInfo) {

        if (addressInfo != null) {
            this.addressInfo = addressInfo;

            addressName.setText(addressInfo.getContact());
            addressPhone.setText(addressInfo.getPhone());
            address.setText(addressInfo.getProvinceName()
                    + addressInfo.getCityName()
                    + addressInfo.getRegionName()
                    + addressInfo.getAddress());

        }
    }

    @Override
    public void setRule(Rule userInfo) {
        if (userInfo != null && userInfo.getContent() != null) {
            MyRichTextHelper.showRich(mContext, userInfo.getContent(), rule, false);
        }
    }
}
